package com.yonyou.uap.um.runtime;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.yonyou.jrmob.application.ui.activity.WebviewActivity;
import com.yonyou.jrmob.lryapp.BlankActivity;
import com.yonyou.jrmob.lryapp.MainActivity;
import com.yonyou.jrmob.lryapp.RTHelperA;
import com.yonyou.jrmob.lryapp.activity.OpenSummerActivity;
import com.yonyou.jrmob.lryapp.login.LoginActivity;
import com.yonyou.uap.um.base.UMEventArgs;
import com.yonyou.uap.um.core.UMActivity;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONObject;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by zhangguang on 2017/3/1.
 */
public class SummerService {

    private static Activity ctx;

    /**
     * 进入h5首页回调(给h5传信息)
     */
    public static void tokenMethod() {
        UMEventArgs args = BaseApp_lib.umeventargs;

        try {
            JSONObject json1 = new JSONObject();

            SharedPreferences mShare = args.getUMActivity().getSharedPreferences(Constant.shared, MODE_PRIVATE);
            UserInfoLRY userInfoLRY = MobUtils.readObject(mShare, Constant.userInfoLry, UserInfoLRY.class);

            if (null != userInfoLRY) {

                json1.put("tenantid", userInfoLRY.getTenant_id());
                json1.put("token", userInfoLRY.getToken());
                json1.put("username", userInfoLRY.getUser_name());
                json1.put("u_usercode", userInfoLRY.getUser_id());


            }

            args.put("result", json1);

            //LogUtils.e("UMEventArgs args: " + args.toJSONObject());
            RTHelperA.execCallBack(args);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String pageParams = "";

    /**
     * h5所有回调都走这个(除刚进入时候的传参数)
     *
     * @param args
     */
    public static void gotoNative(final UMEventArgs args) {

        ctx = args.getUMActivity();
        LogUtils.e(args.toJSONObject().toString());
        Activity ctx = args.getUMActivity();
        JSONObject param = args.getJSONObject("params");

        // 获取transtype
        String transtype = param.optString("transtype", "load_pdf");
        if (TextUtils.isEmpty(transtype)) {
            Toast.makeText(ctx, "tanstype is null", Toast.LENGTH_LONG).show();
            return;
        }

        Intent intent = null;
        Bundle bundle = null;
        // 缓存传的参数
        pageParams = param.optString("pageparam", "");


        if (transtype.equals("pageparam")){
            BaseApp_lib.umeventargs = args;
            try {
                JSONObject json1 = new JSONObject();
                json1.put("pageparam", pageParams );
                args.put("result", json1);
                RTHelperA.execCallBack(args);
            } catch (Exception e) {
                LogUtils.e(e);
                e.printStackTrace();
            }

        }else  if (transtype.equals("takephote")) {  // 相机

            BaseApp_lib.umeventargs = args;

            if (ctx instanceof OpenSummerActivity){
                ((OpenSummerActivity) ctx).TakePhoto();
            }

        } else if (transtype.equals("openalbum")) { //相册
            BaseApp_lib.umeventargs = args;
            if (ctx instanceof OpenSummerActivity){
                ((OpenSummerActivity) ctx).OpenAlbum();
            }

        } else if (transtype.equals("serviceCall")) {// appid 问题
            String innerParams = param.optString("innerParams", "");
            String controllerid = param.optString("controllerId", "com.chamc.ydsp.controller.HRYdspController");
            LogUtils.e("innerParams:" + innerParams);
            LogUtils.e("controllerid:" + controllerid);
            try {
                // 参数
                JSONObject innerParamsjson = new JSONObject(innerParams);
//                innerParamsjson = new JSONObject();
                innerParamsjson.put("controllerid", controllerid);
                innerParamsjson.put("ish5request", "true");
                // 原生的网络请求
                MAServices_gkh.callMACommonService(args.getUMActivity(), new ServiceCallback() {
                    @Override
                    public void execute(JSONObject jsonObject) {
                        LogUtils.e("成功 -> " + jsonObject.toString());
                        try {
                            jsonObject.put("status", "success");
                            args.put("result", jsonObject.toString());
                            RTHelperA.execCallBack(args);

                        } catch (Exception e) {
                            LogUtils.e(e);
                        }
                    }
                    @Override
                    public void error(String s, String s1) {
                        if (null != args) {
                            Toast.makeText(args.getUMActivity(), s1, Toast.LENGTH_LONG).show();
                        }
                        try {
                            JSONObject datacontentjson = new JSONObject();
                            datacontentjson.put("Code", "1");
                            datacontentjson.put("Message", s1);
                            datacontentjson.put("msg", s1);
                            datacontentjson.put("errorcode", "0");
                            datacontentjson.put("errormsg", s1);
                            datacontentjson.put("msg", s1);
                            datacontentjson.put("status", "error");
                            JSONObject datajson = new JSONObject();
                            datajson.put("data", datacontentjson);
                            datajson.put("status", "error");
                            JSONObject resultjson = new JSONObject();
                            resultjson.put("result", datajson);
                            resultjson.put("status", "error");

                            args.put("result", resultjson);
                            RTHelperA.execCallBack(args);

                        } catch (Exception e) {
                            LogUtils.e(e);
                        }

                    }
                }, innerParamsjson);
            } catch (Exception e) {
                LogUtils.e(e);
            }
        } else if (transtype.equals("request_url")) {

            String title2 = param.optString("title", "");
            String startPage = param.optString("startPage", "");
            String appidversion = param.optString("appidversion", "");

            UMActivity umActivity = args.getUMActivity();
            if (null != umActivity) {
                String apkDownloadPath = umActivity.getApplicationContext().getFilesDir().getAbsolutePath() + "/";
                try {
                    Intent intent1 = new Intent(umActivity, OpenSummerActivity.class);
                    intent1.putExtra("appidversion", appidversion + "Update-Date");
                    intent1.putExtra("startPage", startPage);
                    // 启动
                    intent1.putExtra("AndroidFilePath",
                            "file://" + apkDownloadPath + appidversion + "/www/");
                    umActivity.startActivity(intent1);
                } catch (Exception e) {
                    LogUtils.e(e);
                    e.printStackTrace();
                }
            }
        } else if (transtype.equals("timeout_token")) { // h5 token过期
            intent = new Intent(ctx, LoginActivity.class);
            ctx.startActivity(intent);
            ctx.finish();
        } else if (transtype.equals("exit_back")) {  // h5 列表返回键动作
            intent = new Intent(ctx, MainActivity.class);
            ctx.startActivity(intent);
            //ctx.finish();
        } else if (transtype.equals("request_token")) {  //token

//            if (true){
//                if (ctx instanceof OpenSummerActivity){
//                    ((OpenSummerActivity) ctx).TakePhoto();
//                }
//            }

            try {
                BaseApp_lib.umeventargs = args;

                intent = new Intent(ctx, BlankActivity.class); // 去 pdf 界面
                bundle = new Bundle();
                bundle.putString("FileSize", param.optString("FileSize", ""));
                intent.putExtras(bundle);
//                ctx.startActivityForResult(intent,Constant.reuqest_token);
//                ctx.startActivity(intent);
//
//                // 可用接受一些参数
//                RTHelperA.execCallBack(args);
                tokenMethod();

            } catch (Exception e) {
                e.printStackTrace();
            }

//        } else if (transtype.equals("ref_contacts")) { // 通讯录参照
//
//            BaseApp_lib.ref_is_person = true;// 表示是从h5来选人
//            String isSingleSelect = param.optString("isselectsingle", "true");
//            Constant_ct.IS_SELECT_ONLY_ONE = isSingleSelect.equals("true") ? true : false; // 是否多选
//
//            BaseApp_lib.umeventargs = args;
//
//            // 先清空以前选择的情况
//            //Constant_ct.SELECT_LIST = new ArrayList<ContactsVO_ct>();
//
//            // 处理已经从h5选择的人员信息
//            String selectUsers = param.optString("selectusers", "");
//            if (TextUtils.isEmpty(selectUsers)) {
//                LogUtils.i("h5没有已经选择的人员");
//            } else {
//
//                try {
//
//                    JSONArray jsonArray = new JSONArray(selectUsers);
//                    ContactsVO_ct vo;
//                    JSONObject jsonObject = null;
//                    boolean isExist = false;
//                    if (jsonArray == null || jsonArray.length() == 0) {//如果不存在
//                        Constant_ct.SELECT_LIST = new ArrayList<ContactsVO_ct>();//直接清空
//                    } else {
//                        ArrayList<ContactsVO_ct> select_list_copy = new ArrayList<ContactsVO_ct>();
//                        for (int j = 0; j < Constant_ct.SELECT_LIST.size(); j++) {
//                            for (int i = 0; i < jsonArray.length(); i++) {
//                                if (Constant_ct.SELECT_LIST.get(j).getCuserId().equals(jsonArray.getJSONObject(i).optString("contactCode", ""))) {
//                                    isExist = true;//已经存在
//                                    break;
//                                } else {
//                                    isExist = false;//不存在
//                                }
//                            }
//                            if (isExist) {//如果存在则添加到新的集合中
//                                select_list_copy.add(Constant_ct.SELECT_LIST.get(j));
//                                //Constant_ct.SELECT_LIST.remove(j);//如果不存在，则删除
//                            }
//                        }
//                        Constant_ct.SELECT_LIST.clear();
//                        Constant_ct.SELECT_LIST.addAll(select_list_copy);
//                    }
//
//                } catch (Exception e) {
//                    LogUtils.e(e);
//                }
//
//            }
//
//            intent = new Intent(ctx, PickPersonActivity.class);
//            bundle = new Bundle();
//            bundle.putString("FileFlag", param.optString("FileFlag", ""));
//            intent.putExtras(bundle);
//
//            // 设备类型
//
//            String model = eHRApplition.model;
//            //LogUtils.e("model: "+model); // 手机类型
//            //LogUtils.e("info: "+info.toString()); // 手机类型
//            if (model != null && model.startsWith("HM NOTE")){
//                ctx.startActivity(intent);
//            }else{
//                ctx.startActivityForResult(intent, Constant.ref_contacts);
//            }
//
//
//            //LogUtils.e("ctx: " + ctx + " ; param: " + param + " ; args: " + args);
//
//        } else if (transtype.equals("load_pdf")) {  // 打开pdf
//            String fileFlag = param.optString("FileFlag", "");
//            String fileName = param.optString("Filename", "");
//            String title = param.optString("Title", "");
//            String fileUrl = param.optString("FileUrl", "");
//            String fileExt = param.optString("FileExt", "");
//            String fileSize = param.optString("FileSize", "");
//
//            //LogUtils.json(param);
//            //LogUtils.e(param);
////            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
////                    + "/Download/"+ fileName +"."+ fileExt;
//
//            // 要打开文件的完整路径
//            String filePath = ctx.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + Constant.exttype;
//            //filePath = filePath + fileName + "." + fileExt;
//
//            StringBuilder filePathbuilder = new StringBuilder();
//            filePathbuilder.append(filePath);
////            filePathbuilder.append(fileName);
//            filePathbuilder.append(MD5Util.md5Hex(fileUrl));
//            filePathbuilder.append(".").append(fileExt);
//
//
//            // 判断+打开文件
//            OfficeUtil.open(ctx, filePathbuilder.toString(), fileUrl, fileName, fileExt, title);
//
//            //String filePath = mActivity.getStoragePath()+ fileName +"."+ fileExt;
//            /*if(fileExt.equals("pdf")){
//                BaseApp_lib.umeventargs = args;
//                intent = new Intent(ctx, PDFViewActivity.class); // 去 pdf 界面
//                bundle = new Bundle();
//                bundle.putString("FileFlag", fileFlag);
//                bundle.putString("Filename", fileName);
//                bundle.putString("Title", title);
//                bundle.putString("FileUrl", fileUrl);
//                bundle.putString("FileExt", fileExt);
//                bundle.putString("FileSize", fileSize);
//                intent.putExtras(bundle);
//                ctx.startActivity(intent);
//            }else{*/
//
//            //}
//        }else if (transtype.equals(Constant.timeouttoken)){  // token 过期 transtype
//
//
//            try {
//
//                JSONObject json = new JSONObject();
//                json.put("type", Constant.timeouttoken);
//                // 发送信息
//                EventBus.getDefault().post(json);
//
//            } catch (Exception e) {
//                LogUtils.e(e);
//            }
        } else if (transtype.equals("openUrl")){
            UMActivity umActivity = args.getUMActivity();
            String openurl = param.optString("url", "");
            Intent intent1 = new Intent(umActivity, WebviewActivity.class);
            intent1.putExtra(WebviewActivity.INTENT_URL, openurl);
            umActivity.startActivity(intent1);
        }



    }


    public static void returnFinish(UMEventArgs args) {
        //LogUtils.e(args.toJSONObject());
        RTHelper.execCallBack(args);
    }


}


